<?php

namespace app\utils;

use yii\web\UploadedFile;

/**
 * 公共方法类
 * Class Utils
 * @package app\utils
 */
class Utils extends \yii\base\BaseObject
{
    /**
     * 根据当前时间返回问候语
     * @method getHaloWord
     * @return string
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/25 11:29
     */
    public static function getHaloWord()
    {
        $hours = date('H', time());

        if ($hours >= 18 || $hours < 5) {
            return '晚上好！';
        } elseif ($hours >= 12) {
            return '下午好！';
        } elseif ($hours >= 5) {
            return '早上好！';
        }
    }

    /**
     * 生成工单号
     * @method generateOrderNo
     * @param $prefix 工单号前缀
     * @param $id ID
     * @return string
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/14 9:00
     */
    public static function generateOrderNo($prefix, $id)
    {
        return "{$prefix}_00{$id}";
    }

    /**
     * 工单号处理为ID
     * @method getNumeric
     * @param $order_no 工单号
     * @param $prefix 前缀
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/14 8:43
     */
    public static function getNumeric($order_no = '', $prefix = '[A-Z]+')
    {
        $match = preg_match("/{$prefix}_00([0-9]+)/i", $order_no, $matches);
        return $match ? $matches[1] : '';
    }

    public static function formUnserialize($serialize = '')
    {
        if ($serialize) {

            $data = [];
            foreach (json_decode($serialize, true) as $key => $val) {
                $data[$val['name']] = htmlspecialchars($val['value']);
            }
            if (isset($data['searchData'])) {
                unset($data['searchData']);
            }
            return $data;
        } else {
            return false;
        }
    }

    public static function uploadFile()
    {
        //根目录
        $base_path = \Yii::$app->basePath . '/web/';
        //相对路径
        $save_path = 'attachment/' . date('Ymd') . '/';
        //绝对路径
        $patch = $base_path . $save_path;

        if (!file_exists($patch)) {
            mkdir($patch, 0777, true);
        }

        $tmp_file = UploadedFile::getInstanceByName('file');

        if ($tmp_file) {
            //文件名称
            $file_name = \Yii::$app->getSecurity()->generateRandomString() . '.' . $tmp_file->getExtension();
            $tmp_file->saveAs($patch . $file_name);
        }

        return $save_path . $file_name;
    }

    public static function setCookie($name, $value, $expire = 0)
    {
        $cookies = \Yii::$app->response->cookies;
        return $cookies->add(new \yii\web\Cookie([
            'name' => $name,
            'value' => $value,
            'expire' => $expire,
        ]));

    }

    public static function getCookie($name)
    {
        $cookies = \Yii::$app->request->cookies;
        return $language = $cookies->get($name) ? $cookies->get($name)->value : false;
    }
}
